from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from libs.captcha.captcha import Captcha
# from libs.yuntongxun.sms import CCP
from django_redis import get_redis_connection


# Create your views here.

class RegisterImagecodeAPIView(APIView):

    def get(self,request,image_code_id):
        text,image = Captcha().generate_captcha() #生成验证码及其图片
        redis = get_redis_connection('code')
        redis.setex('img_%s'%image_code_id,300,text)  #将验证码信息保存到redis 2号库，有效5分钟

        return HttpResponse(content=image,content_type='image/jpeg')


from .serializers import RegisterSmscodeSerializer
class RegisterSmscodeAPIView(GenericAPIView):
    serializer_class = RegisterSmscodeSerializer

    def get(self,request,mobile):

        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        import random
        sms_code = '%06d'%random.randint(0,999999)

        redis = get_redis_connection('code')
        redis.setex('sms_%s'%mobile,300,sms_code)

        # CCP().send_template_sms(mobile,[sms_code,5],1)
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)

        return Response({'message':'OK'})




